package cn.shujuhai.qtadmin.platform.config;

import java.time.LocalDateTime;

import org.apache.ibatis.reflection.MetaObject;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;

import lombok.extern.slf4j.Slf4j;

/**
 * MyMetaObjectHandler
 *
 * @author dch798
 * @date 2021/09/23 15:36
 **/
@Slf4j
@SpringBootConfiguration
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("start insert fill ....");
        this.strictInsertFill(metaObject, "created", LocalDateTime.class, LocalDateTime.now());
        var user = "anonymousUser";
        var auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            UserDetails userDetails =
                (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            user = userDetails.getUsername();
        }
        this.strictInsertFill(metaObject, "creator", String.class, user);

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("start update fill ....");
        this.strictInsertFill(metaObject, "edited", LocalDateTime.class, LocalDateTime.now());
        var user = "anonymousUser";
        var auth = SecurityContextHolder.getContext().getAuthentication();
        if (!(auth instanceof AnonymousAuthenticationToken)) {
            UserDetails userDetails =
                (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            user = userDetails.getUsername();
        }
        this.strictInsertFill(metaObject, "editor", String.class, user);
    }
}
